package com.project.psc.controller;

import com.alibaba.fastjson.JSON;
import com.project.psc.bean.CheckBean;
import com.project.psc.bean.SupplierBean;
import com.project.psc.dto.SupplierDto;
import com.project.psc.service.ISupplierService;
import com.project.psc.util.SupplierThreadLocal;
import com.project.psc.vo.LoginVo;
import com.project.util.CreateToken;
import com.project.vo.ResultVo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@RestController
@RequestMapping("supplier")
public class SupplierController {
    @Autowired
    private ISupplierService supplierService;


    @PostMapping("register")
    public ResultVo register(@RequestBody SupplierBean supplierBean) {
        boolean register = supplierService.register(supplierBean);
        if (register) {
            return ResultVo.ok();
        }
        return ResultVo.fail("用户名已存在");
    }

    @GetMapping("findById")
    public ResultVo findById(HttpServletRequest req){

        SupplierDto loginUser = SupplierThreadLocal.getSupplier();


        if (loginUser!=null){
            return ResultVo.ok(supplierService.findById(loginUser.getId()));
        }
        return ResultVo.ok();
    }


    @GetMapping("login")
    public ResultVo login(String userName, String password, HttpServletRequest req) throws NoSuchAlgorithmException {
        SupplierDto loginSupplier = supplierService.login(userName, password);
        LoginVo loginVo = new LoginVo();
        if (loginSupplier != null) {//用户存在
            if (loginSupplier.getStatus() == 0) {
                return ResultVo.fail("注册信息正在审核中，请稍后再试");
            }

            loginVo.setStatus(loginSupplier.getStatus());
            String json= JSON.toJSONString(loginSupplier);
            String token = CreateToken.createToken(json);
            loginVo.setToken(token);

//            req.getSession().setAttribute("loginUser", loginSupplier);
            return ResultVo.ok(loginVo);
        }
        return ResultVo.fail("用户名或密码输入错误");
    }


    @GetMapping("findErr")
    public ResultVo findErr() {
        SupplierDto loginUser = SupplierThreadLocal.getSupplier();
        List<CheckBean> reasons = supplierService.findReasons(loginUser.getId());
        return ResultVo.ok(reasons);
    }
}
